<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Models\Voucher;
use Auth;
use Carbon\Carbon;
use Illuminate\Http\Request;
use QrService;

class TradeController extends Controller
{

    //出示二维码
    public function showQr(Request $request, Voucher $voucher)
    {
        //这里需要指定前端跳转的路径（这里用后台测试地址）
//        $url = url('admin/voucher/' . $voucher->uuid . '/verify');
        $url = 'trade/voucher/' . $voucher->uuid . '/send';
        $type = $voucher->type;
        $voucher->save();
        $qr = QrService::init($url, $type)->make();
        return $qr;
    }

//发送领取请求
    public function send(Voucher $voucher)
    {
        //1、已兑换，不能转移，2、已失效不能转移，3、也存在不能重复转移

        $status = 0;
//        当前状态：0：待激活；1：可使用，2：待兑换，3：已兑换，4：已失效');

        if ($voucher->status == 3) {
            return $this->error('代金券已兑换');
        } else if ($voucher->status == 4) {
            return $this->error('代金券已失效');
        } else if (Auth::user()->vouchers()->find($voucher->id, 'uuid')) {
            return $this->error('已经领取，请勿重复操作');
        }

        if ($voucher->times == 0) {
            $status = 1;

        } elseif ($voucher->times >= 3) {
            $status = 2;
        }


        $voucher->update([
            'user_id' => Auth::id(),
            'times' => $voucher->times + 1,
            'status' => $status
        ]);
        return $this->message('领取成功');
    }


    //提现方法
    public function withdraw(Voucher $voucher)
    {
        //1、已兑换，不能转移，2、已失效不能转移，3、也存在不能重复转移
        $isOvertime = (new Carbon)->diffInMinutes($voucher->overtime, true) < 0;

        if ($isOvertime) {
            //是否已经过期
            return $this->error('代金券已失效，无法兑换');
        }
        if ($voucher->status == 3) {
            return $this->error('代金券已兑换');
        }
        if ($voucher->times < 3) {
            //转移次数小于3次
            return $this->error('流通次数小于3次');
        }

        $voucher->update([
            'user_id' => Auth::id(),
            'times' => $voucher->times + 1,
            'status' => 3,
        ]);
        return $this->message('兑换成功');
    }
}
